package com.navidove.appsportlight.test;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import com.navidove.appspotlight.model.bo.AppDevice;
import com.navidove.appspotlight.model.bo.AppItem;
import com.navidove.appspotlight.model.bo.AppDevice.DeviceType;
import com.navidove.appspotlight.model.bo.SysImage;
import com.navidove.appspotlight.model.dao.AppDeviceDao;
import com.navidove.appspotlight.model.dao.AppItemDao;
import com.navidove.appspotlight.model.dao.SysImageDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/spring/spring.xml" })
public class ImportImageFile {
	
	private String dir= "D:/ray/upload";
	
	@Autowired
	private AppItemDao appItemDao;
	
	@Autowired
	private AppDeviceDao appDeviceDao;
	
	@Autowired
	private SysImageDao sysImageDao;
	
	@Test
	@Rollback(false)
	@Transactional
	public void doTest() throws IOException {
		File folder = new File(dir);
		
	    String[] names = folder.list();	    
	    for (String name : names) {
	    	try {
		    	String[] fields = name.split("_");
		    	
		    	String appName = fields[0];
		    	String device = fields[1];
		    	DeviceType deviceType = DeviceType.valueOf(device.toUpperCase());
		    	String imgName = FilenameUtils.getBaseName(fields[2]);
		    	File file = new File(folder,name);
		    	
		    	AppItem appItem = getAppItem(appName);
		    	if(appItem == null) {
		    		System.out.println(appName);
		    		System.out.println(name);
		    	}
		        AppDevice appDevice = getAppDevice(appItem, deviceType);
		        SysImage sysImage = getImage(appDevice, imgName, file);
				if ("qrc".equals(imgName)) {
					appDevice.setQrcImage(sysImage);
				} else if ("icon".equals(imgName)) {
					appDevice.setIconImage(sysImage);
				}
				appDeviceDao.save(appDevice);
	    	} catch (Exception e) {
	    		System.out.println(name);
	    		throw new IllegalStateException(e);
	    	}

	    	
	    }
		
	}
	
	Map<String, AppItem> appItemMap = new HashMap<String, AppItem>();
	
	protected AppItem getAppItem(String appName) {
		if (appItemMap.get(appName.toUpperCase())!=null) {
			return appItemMap.get(appName.toUpperCase());
		}
		appItemMap.put(appName.toUpperCase(),appItemDao.get(Restrictions.eq("appName", appName).ignoreCase()));
		
		return appItemMap.get(appName.toUpperCase());
	}
	
	protected AppDevice getAppDevice(AppItem appItem, DeviceType deviceType){
		DetachedCriteria criteria = DetachedCriteria.forClass(AppDevice.class);
		
	    criteria.add(Restrictions.eq("appItem", appItem));
	    criteria.add(Restrictions.eq("deviceType", deviceType));
	    
	    Date now = new Date();
	    AppDevice val = (AppDevice) appDeviceDao.getByCriteria(criteria);
	    if (val == null) {
	    	val = new AppDevice();
	    	val.setDeviceType(deviceType);
	    	val.setCrtAt(now);
	    	val.setAppItem(appItem);
	    }
	    val.setUpdAt(now);
	    appDeviceDao.save(val);
	    return val;
	}
	
	protected SysImage getImage(AppDevice appDevice, String imgName, File file) {
		Date now = new Date();
		
		SysImage sysImage = null;
		if ("qrc".equals(imgName)) {
			sysImage = appDevice.getQrcImage();
		} else if ("icon".equals(imgName)) {
			sysImage = appDevice.getIconImage();
		}
		
		if (sysImage == null) {
			sysImage = new SysImage();
			sysImage.setCrtAt(now);			
		}
		
		sysImage.setFileName(file.getName());
		try {
			sysImage.setContent(FileUtils.readFileToByteArray(file));
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
		sysImage.setFileSize((int)file.length());
		sysImage.setEnable(Boolean.TRUE);
		sysImage.setMime(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file));
		sysImage.setUpdAt(now);
		sysImageDao.save(sysImage);
		
		return sysImage;
	}
}
